<template>
    <div id="custometable">
        <!--客户管理头部-->
        <el-row class="head">
            <el-col :span="24">
                <h1 class="contract_title" >客户管理</h1>
                <span>/ 管理客户相关信息</span>
            </el-col>
        </el-row>
        <!--客户管理中间部分-->
        <div class="nav">
            <div class="nav-item">
                <el-button type="text" @click="open_add_cus">
                    <i class="iconfont icon-qianbi">  新增</i>
                </el-button>
            </div>
            <!--  <div class="nav-item">
               <el-button type="text" @click="mergeObject">
                   <i class="iconfont icon-qianbi">  合并</i>
               </el-button>
           </div>
        <div class="nav-item">
               <el-dropdown :hide-on-click="false">
                   <span class="el-dropdown-link">
                       <i class="iconfont icon-lanmu">  更多关联数据</i>
                       <i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>
                   </span>
                   <el-dropdown-menu slot="dropdown">
                       <el-dropdown-item>  客户购买商品汇总</el-dropdown-item>
                       <el-dropdown-item>  信息表</el-dropdown-item>
                       &lt;!&ndash;,params:{catId:0},query:{keywords:'手机'} 简单测试&ndash;&gt;

                       <router-link tag="a"  :to="{path:'/customer_view'}">   <el-dropdown-item>  客户需求(视图)</el-dropdown-item></router-link>
                       <el-dropdown-item>  沟通记录</el-dropdown-item>
                       <el-dropdown-item>  客户信息添加</el-dropdown-item>
                   </el-dropdown-menu>
               </el-dropdown>
           </div>-->
         <!--   <div class="nav-item">
                <el-dropdown :hide-on-click="false">
                    <span class="el-dropdown-link">
                        <i class="iconfont icon-m-weixinwenzhang">  更多操作</i>
                        <i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown" >
                        <el-dropdown-item>批量分配</el-dropdown-item>
                        <el-dropdown-item>批量编辑</el-dropdown-item>
                        <el-dropdown-item>批量删除</el-dropdown-item>
                        <el-dropdown-item>获取公海客户</el-dropdown-item>
                        <el-dropdown-item>客户转移历史</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>

            <div class="nav-item">
                <el-upload action="" :on-change="handleChange"
                           :on-exceed="handleExceed"
                           :limit="1"
                           :show-file-list="false"
                           :auto-upload="false">
                    <el-button type="text">
                        <i class="iconfont icon-excel">  导入</i>
                    </el-button>
                </el-upload>
            </div>-->
            <div class="nav-item">
                <download-excel :data="allCustomer" :fields="excelFields" name="客户列表.xls" type="xls">
                    <el-button type="text">
                        <i class="iconfont icon-excel">  导出</i>
                    </el-button>
                </download-excel>
            </div>
            <div class="nav-item">
            <el-form style="display:inline-block; font-size:12px">
                <div class="nav-item nav-input" style="border:none">
                    <el-input v-model="searchParam" @change="searchCustomer"></el-input>
                </div>
                <div style="display:inline-block;">
                    <el-button class="nav-butt">搜索</el-button>
                </div>
            </el-form>
            </div>
        </div>

        <!--客户管理导航部分 tabs-->
        <div class="content" v-loading="loading">
            <el-tabs v-model="activeName" type="border-card" :data="stage_data" @tab-click="naviClick">
                <el-tab-pane   name="first" stageId = "0">
                    <span slot="label"><i class="iconfont icon-kehu">  全部</i></span>
                    <custome-table :customers="customer_data"  :home = "this" @sendcusType="getcusType"  ref="cusTableRef" ></custome-table>
                </el-tab-pane>
                <el-tab-pane   v-for="(item, index) in stage_data" :key="item.stageId" :label="item.stageName" :name="item.activeName" :stageId = "item.stageId">
                    <span  slot="label">{{item.stageName}}</span>
                    <custome-table :customers="customer_data" :home = "this" @sendcusType="getcusType" > </custome-table>
                </el-tab-pane>
                <!--分页-->
                <div class="block" style="margin-top:10px">
                    <el-pagination background layout="total, prev, pager, next"
                                   :total="total"
                                   :current-page.sync="curr_page"
                                   :page-size="page_size"
                                   @current-change="changge_page">
                    </el-pagination>
                </div>
            </el-tabs>
        </div>
        <!--新增客户-->
        <el-dialog v-dialogDrag :visible.sync="customerinfoVisible" width="50%" title="新增客户" :modal="false" :close-on-click-modal="false" class="paddchang" @close="closeCusAdd">
            <add_customer_info ref="addCus"></add_customer_info>
        </el-dialog>
        <!--导入弹框-->
        <el-dialog v-dialogDrag :visible.sync="excelVisible" width="60%" title="导入客户信息" :modal="false" :close-on-click-modal="false" class="paddchang" destroy-on-close>
            <el-table border :data="excelData" tooltip-effect="dark" style="width: 100%">
                <el-table-column prop="contactId" type="selection" width="70" header-align="center" align="center"></el-table-column>
                <el-table-column prop="customerName" label="客户名称" header-align="center" align="center"></el-table-column>
                <el-table-column prop="cusType.customerType" label="客户类型" header-align="center" align="center"></el-table-column>
                <el-table-column prop="contact[0].contactName"  label="主联系人"  header-align="center" align="center"></el-table-column>
                <el-table-column prop="contact[0].contactTel"  label="电话" header-align="center" align="center"></el-table-column>
                <el-table-column prop="contact[0].contactPhone" label="手机" header-align="center" align="center"></el-table-column>
                <el-table-column prop="owner.empName" label="业务员" header-align="center" align="center"></el-table-column>
                <el-table-column  label="操作" header-align="center" align="center">
                    <template slot-scope="s">
                        <el-button type="primary" size="small" icon="el-icon-edit" circle @click="editLinkMan(s.row)"></el-button>
                        <el-button type="danger" size="small"  icon="el-icon-delete" circle ></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-button > 确认导入</el-button>
            <el-button > 取消</el-button>
        </el-dialog>

    </div>
</template>
<script>
    import custometable from "./custometable.vue";
    import add_customer_info from "./add_customer_info";
    import {formatTimeToStr} from "../../assets/format";

    export default{
    data:function () {
        return {
            loading:true,
            dot:true,
            // excel导入
            fileTemp: null,
            file: null,
            da: [],
            dalen: 0,
            excelData: {},
            excelVisible:false,
            // 导出excel
            allCustomer: [],			// 全部的客户数据（非分页数据），用于导出excel
            excelFields: {			// excel对应关系
                "客户名称": "customerName",		// 支持嵌套属性
                "客户类型": "cusType.customerType",
                "主联系人":{
                    field:"contact",
                    callback: value => {
                      if(value.length != 0){
                          return value[0].contactName
                      }else {
                          return '无'
                      }
                    }
                },
                "联系电话": {
                    field:"contact",
                    callback:value => {
                        if(value.length != 0){
                            return value[0].contactTel
                        }else {
                            return '无'
                        }
                    }
                },
                "手机": {
                    field:"contact",
                    callback:value => {
                        if(value.length != 0){
                            return value[0].contactPhone
                        }else {
                            return '无'
                        }
                    }
                },		// 常规字段
                "业务员": "owner.empName",
        },
        customerinfoVisible:false,//新增客户对话框
        stage_data:[], //客户阶段信息
        customerType:'',
        page_size:5,
        total:0,
        curr_page:1,
        searchParam:'',
        stageId:0,
        customer_data:[],//所有客户信息
        activeName:"first",//导航tabs 的标识
            tar:{}
    }
},
    methods:{
        //合并
        mergeObject(){
            console.log("父页面拿到的合并对象");
            console.log(this.$refs.cusTableRef.objList);
            let length = this.$refs.cusTableRef.objList.length
            for(var i=0; i<length; i++){
                this.tar = Object.assign(this.tar, this.$refs.cusTableRef.objList[i]);
                console.log(this.tar)
            }
           console.log("合并的对象");
           console.log(this.tar)
        },
        //上传文件时处理方法
        handleChange(file){
            this.fileTemp = file.raw;
            if(this.fileTemp){
                window.console.log('拿到的文件类型：')
                window.console.log(this.fileTemp.type)
                this.importfxx(this.fileTemp);
                this.excelVisible = true

            } else {
                this.$message({
                    type:'warning',
                    message:'请上传附件！'
                })
            }
        },
        //超出最大上传文件数量时的处理方法
        handleExceed(){
            this.$message({
                type:'warning',
                message:'超出最大上传文件数量的限制！'
            })
            return;
        },
        // 导入excel
        importfxx(obj) {
            let _this = this;
            let inputDOM = this.$refs.inputer;
            // 通过DOM取文件数据
            this.file = event.currentTarget.files[0];
            var rABS = false; //是否将文件读取为二进制字符串
            var f = this.file;

            var reader = new FileReader();
            FileReader.prototype.readAsBinaryString = function(f) {
                var binary = "";
                var rABS = false; //是否将文件读取为二进制字符串
                var pt = this;
                var wb; //读取完成的数据
                var outdata;
                var reader = new FileReader();
                reader.onload = function(e) {
                    var bytes = new Uint8Array(reader.result);
                    var length = bytes.byteLength;
                    for (var i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i]);
                    }
                    //此处引入，用于解析excel
                    var XLSX = require("xlsx");
                    if (rABS) {
                        wb = XLSX.read(btoa(fixdata(binary)), {
                            //手动转化
                            type: "base64"
                        });
                    } else {
                        wb = XLSX.read(binary, {
                            type: "binary"
                        });
                    }
                    outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                    window.console.log('拿到的excel中的客户数据：')
                    window.console.log(outdata)
                    //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
                    let arr = []
                    outdata.map(v => {
                        let customer = {cusType:{}, contact:[],owner:{}}
                        let con ={}
                        customer.customerName = v['客户名称']
                        customer.cusType.customerType = v['客户类型']
                        con.contactName = v['主联系人'] //这里不能出现contact[0]
                        con.contactTel = v['电话']
                        con.contactPhone = v['手机']
                        customer.contact.push(con)
                        customer.owner.empName = v['业务员']
                        arr.push(customer)
                    })
                    _this.excelData = arr
                    window.console.log('excelData数据：')
                    window.console.log(_this.excelData )
                    this.fileTemp = null
                };
                reader.readAsArrayBuffer(f);
            };
            if (rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
        },
        //获取全部客户数据用于导出
        getAllCustomer(){
            this.axios.get("api/customer/find-cusinfo",{params:{"currPage":this.curr_page,"pageSize":99999,"search":this.search,"cusTypeName":this.customerType,"stageId":this.stageId}})
        .then(v => {
                        this.allCustomer = v.data.data
            console.log("this.allCustomer:");
                        console.log(this.allCustomer);
                    }).catch()
        },
        /*axios获取所有客户信息*/
        get_customers_data(curr_page,page_size,search,customerType,stageId){
            this.axios.get("api/customer/find-cusinfo",{params:{"currPage":curr_page,"pageSize":page_size,"search":search,"cusTypeName":customerType,"stageId":stageId}})
                .then(v => {
                    //获取所有客户
                    this.customer_data = v.data.data;
                    this.total=v.data.total;
                    this.loading = false
                })
                .catch(() => {
                    this.loading = false
                    this.global.mes_error("客户信息获取失败！")
                })


        },
        naviClick(demo){
            this.customerType = 0 //可重置客户类型
           this.stageId = demo.$attrs.stageId
            this.get_customers_data(1,this.page_size,this.searchParam,this.customerType,demo.$attrs.stageId)
        },
        /*查询所有客户阶段*/
        getAllStage(){
            this.axios.get("api/customer/all_stage")
                .then(v => {
                    this.stage_data = v.data;
                    this.loading = false
                }).catch()
        },
        /*分页事件*/
        changge_page(curr){
            this.get_customers_data(curr,this.page_size,this.searchParam,this.customerType,this.stageId);
        },
        /*抽屉中添加行动记录的弹框*/
        addAction(){
           this.actionVisible = true;
        },
        /*点击标签回值到input文本框中*/
        check_mark(){

        },
        //搜索框
        searchCustomer(){
            this.get_customers_data(1,this.page_size,this.searchParam,this.customerType,this.stageId );
        },
        //接收从customertable传过来的客户类型
        getcusType(data){
            this.customerType = data
            this.get_customers_data(this.curr_page,this.page_size,this.searchParam,this.customerType,this.stageId);
        },
        open_add_cus(){
            this.customerinfoVisible = true;
            //将本页面数据存入store
            this.$store.dispatch("setVueCusMan",this)

        },
        closeCusAdd(){
            this.$refs.addCus.clearCus() //关闭页面清空数据
        }

    },
        components:{
            add_customer_info,
            'custome-table':custometable,
            /*'add-actform':add-actform*/
        },
        created:function(){
            this.get_customers_data(1,this.page_size,this.searchParam,this.customerType,this.stageId);
            this.getAllStage();
            this.getAllCustomer();
        }

    }

    /* let routeData = this.$router.resolve({
 name: "customerView"/!*,
 query: params,
 params:{catId:params.catId}*!/
 });
 window.open(routeData.href, '_blank');*/
</script>
<style scoped>
.notoucher{ width:330px; height:60px;padding: 15px; border: 1px solid transparent;}
.notoucher .alert{ border-radius: 3px; width: 100%;height: 100%;  color: #31708f;padding: 20px 20px 10px 20px;
    background-color: #d9edf7;
    border-color: #bce8f1;}
.nochance .alert{ border-radius: 3px; width: 100%;height: 100%; padding: 20px 20px 10px 20px;color: #a94442;
    background-color: #f2dede;
    border-color: #ebccd1;}


    * {margin: 0;padding: 0; font-size: 14px;}
.contract_main {background: #e4e7ee;}
.head {height: 70px;background: #f8f6f8;line-height: 70px;}
.contract_title {display: inline-block;font-weight: unset;margin-left: 20px; }
.el-col span {color: #b4b4bc;margin-left: 8px}
.nav {margin: 20px;background: #fcfbfd;width: 100%-40px;height:auto!important;min-height: 15px;line-height: 45px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);}
.nav .nav-item {display: inline-block;height: 45px;padding: 0px 10px;    border-right: 1px solid #eee;line-height: 45px;}
.content {margin: 20px;background: #fcfbfd;width: 100%-40px;min-height:10px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);}
#app> section> section> main> div> div.content> div> div .el-tabs__header .is-top { margin: 0 !important;}
.el-button--text {color: #606266;font-size: 12px;padding: 6px 0;}
.nav{

    min-height: 20px;
    height: 50px;
    line-height: 50px;
}
.el-dropdown-menu__item{
    font-size: 12px;
}
a,button,input{-webkit-tap-highlight-color:rgba(255,0,0,0);}
.action .hftime{height:39px;line-height: 40px; width:80%;margin: 20px 20px; border-radius: 5px;border: 1px solid #DCDFE6;padding-left: 20px;    color: #a94442;
  background-color: #f2dede;
  border-color: #ebccd1;}
.el-checkbox-button{ padding:10px 10px;  border-radius: 4px; border: 1px solid #DCDFE6;}

.action .record{ position: relative;top:-47px;right:-18px; }
.action .el-select-dropdown {width: 112%;}
.action .el-textarea {margin: 20px 20px;width:85%;}
.action .el-tab-pane{padding: 20px 20px;}
.action .el-select{width: 76%;margin-left: 20px;}
.customName{font-family: Microsoft YaHei, SimSun;font-weight: bold;font-size: 16px;padding-left: 12px;line-height: 21px;color: #636e7b;}
.more{font-size: 16px;color: black;line-height: 21px}
.actP {border-radius: 10px;border: solid 1px #dedede;padding: 10px;margin-bottom: 10px;}
.actP table {width: 100%;background-color: transparent;border-spacing: 0;border-collapse: collapse;border-width: 0;}
table td {padding: 5px;}
.actP .pi {vertical-align: top;}
.actP .el-image {width: 40px;height: 40px;border-radius: 50%;vertical-align: middle;border: 0;}
.actP .pn {border-bottom: #ddd 1px solid;font-size: 1.2em;font-weight: bold;}
.actP .pn i {padding: 0px 6px;}
.el-dropdown-link{color:#606266 !important;}
.text {
    font-size: 14px;
}
.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}
.clearfix:after {
    clear: both
}
.clearfix{}
.en{padding-left: 10px;min-width:2px;  height:30px;line-height:30px; }
    .box-card  .time { position: relative; left: 150px   }
    .box-card {
        width: 360px;
        margin: 20px 20px;
    }
.content{
    -webkit-box-shadow: none;
    box-shadow: none;
}


</style>